package com.cqeec.netdisc0215.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.openstack4j.api.OSClient.OSClientV3;
import org.openstack4j.model.storage.object.SwiftContainer;
import org.openstack4j.model.storage.object.SwiftObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.cqeec.netdisc0215.bean.FileInfoBean;
import com.cqeec.netdisc0215.model.User;
import com.cqeec.netdisc0215.util.OpenStackClientUtil;

@Controller
public class MainController {
	@RequestMapping("/main")
	public String gotoMainPage() {
		return "redirect:/main/list";
	}

	@RequestMapping("/main/thumbnail")
	public ModelAndView thumbnailAllFile(HttpSession session) {
		ModelAndView mav = new ModelAndView("thumbnail");
		Object obj = session.getAttribute("user");
		if (obj == null) {
			mav.setViewName("redirect:/login");
		} else {
			User user = (User) obj;
			List<FileInfoBean> files = getFiles(session, user);
			mav.addObject("files", files);
		}
		return mav;
	}

	@RequestMapping("/main/list")
	public ModelAndView listAllFile(HttpSession session) {
		ModelAndView mav = new ModelAndView("main");
		Object obj = session.getAttribute("user");
		if (obj == null) {
			mav.setViewName("redirect:/login");
		} else {
			User user = (User) obj;
			List<FileInfoBean> files = getFiles(session, user);
			mav.addObject("files", files);
		}
		return mav;
	}

	private List<FileInfoBean> getFiles(HttpSession session, User user) {
		List<FileInfoBean> files = new ArrayList<FileInfoBean>();
		// 获取对应容器的文件
		OSClientV3 os = OpenStackClientUtil.getOSClient();
		List<? extends SwiftContainer> containers = os.objectStorage().containers().list();
		for (SwiftContainer container : containers) {
			if (container.getName().equals(user.getLoginName())) {
				List<? extends SwiftObject> objects = os.objectStorage().objects().list(container.getName());
				FileInfoBean fib;
				for (SwiftObject object : objects) {
					fib = new FileInfoBean();
					fib.setContainerName(object.getContainerName());
					fib.setDirectoryName(object.getDirectoryName());
					fib.setName(object.getName());
					fib.setMimeType(object.getMimeType());
					fib.setSizeInBytes(object.getSizeInBytes());
					fib.setLastModified(object.getLastModified());
					fib.setIsDirectory(object.isDirectory());
					files.add(fib);
				}

				break;
			}
		}
		return files;
	}
}